"use client"

import type React from "react"

import { useState, useRef } from "react"
import Image from "next/image"
import Link from "next/link"
import {useParams, useRouter} from "next/navigation"
import { formatNumber, formatDuration } from "@/lib/format"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import {
    Heart,
    Share2,
    MessageSquare,
    Download,
    ListPlus,
    Play,
    Pause,
    Volume2,
    VolumeX,
    Maximize2,
    SkipBack,
    SkipForward,
} from "lucide-react"
import CommentSection from "@/components/comments/shared/comment-section"
import { toast } from "@/components/ui/use-toast"

export default function MVDetailPage() {
    const [isPlaying, setIsPlaying] = useState(false)
    const [isMuted, setIsMuted] = useState(false)
    const [currentTime, setCurrentTime] = useState(0)
    const [duration, setDuration] = useState(0)
    const [isLiked, setIsLiked] = useState(false)
    const videoRef = useRef<HTMLVideoElement>(null)
    const router = useRouter()
    const { id } = useParams()
    // 模拟MV详情数据
    const mvDetail = {
        id: id,
        title: "告白气球",
        artists: "周杰伦",
        artistId: "1",
        cover: "/placeholder.svg?height=720&width=1280",
        url: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", // 示例视频
        duration: 215,
        releaseDate: "2016-07-15",
        playCount: 10000000,
        likes: 500000,
        comments: 25000,
        shares: 15000,
        description:
            "《告白气球》是周杰伦演唱的一首歌曲，收录于专辑《周杰伦的床边故事》中。这首歌曲由周杰伦作曲，方文山作词。MV中周杰伦化身为魔术师，在巴黎铁塔下用魔术向心爱的女孩表白。",
        lyrics: [
            { time: 0, text: "[00:00.00] 作词 : 方文山" },
            { time: 2, text: "[00:02.00] 作曲 : 周杰伦" },
            { time: 4, text: "[00:04.00] 编曲 : 周杰伦" },
            { time: 15, text: "[00:15.00] 塞纳河畔 左岸的咖啡" },
            { time: 19, text: "[00:19.00] 我手一杯 品尝你的美" },
            { time: 23, text: "[00:23.00] 留下唇印的嘴" },
            { time: 30, text: "[00:30.00] 花店玫瑰 名字写错谁" },
            { time: 34, text: "[00:34.00] 告白气球 风吹到对街" },
            { time: 38, text: "[00:38.00] 微笑在天上飞" },
            { time: 45, text: "[00:45.00] 你说你有点难追 想让我知难而退" },
            { time: 49, text: "[00:49.00] 礼物不需挑最贵 只要香榭的落叶" },
        ],
        tags: ["流行", "华语", "告白", "浪漫"],
    }

    // 模拟相关MV数据
    const relatedMVs = [
        {
            id: "2",
            title: "不爱我就拉倒",
            artists: "周杰伦",
            artistId: "1",
            cover: "/placeholder.svg?height=300&width=300",
            duration: 198,
            playCount: 8500000,
        },
        {
            id: "3",
            title: "说好不哭",
            artists: "周杰伦",
            artistId: "1",
            cover: "/placeholder.svg?height=300&width=300",
            duration: 224,
            playCount: 9200000,
        },
        {
            id: "4",
            title: "Mojito",
            artists: "周杰伦",
            artistId: "1",
            cover: "/placeholder.svg?height=300&width=300",
            duration: 186,
            playCount: 7800000,
        },
        {
            id: "5",
            title: "等你下课",
            artists: "周杰伦",
            artistId: "1",
            cover: "/placeholder.svg?height=300&width=300",
            duration: 269,
            playCount: 6500000,
        },
    ]

    // 处理视频播放控制
    const togglePlay = () => {
        if (videoRef.current) {
            if (isPlaying) {
                videoRef.current.pause()
            } else {
                videoRef.current.play()
            }
            setIsPlaying(!isPlaying)
        }
    }

    const toggleMute = () => {
        if (videoRef.current) {
            videoRef.current.muted = !isMuted
            setIsMuted(!isMuted)
        }
    }

    const handleTimeUpdate = () => {
        if (videoRef.current) {
            setCurrentTime(videoRef.current.currentTime)
        }
    }

    const handleLoadedMetadata = () => {
        if (videoRef.current) {
            setDuration(videoRef.current.duration)
        }
    }

    const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
        const newTime = Number.parseFloat(e.target.value)
        if (videoRef.current) {
            videoRef.current.currentTime = newTime
            setCurrentTime(newTime)
        }
    }

    const toggleLike = () => {
        setIsLiked(!isLiked)
    }

    // 全屏播放
    const handleFullscreen = () => {
        if (videoRef.current) {
            if (document.fullscreenElement) {
                document.exitFullscreen()
            } else {
                videoRef.current.requestFullscreen()
            }
        }
    }

    // 处理分享
    const handleShare = () => {
        try {
            // 准备分享数据
            const shareResource = {
                id: mvDetail.id,
                type: "mv",
                title: mvDetail.title,
                artist: mvDetail.artists,
                cover: mvDetail.cover,
            }

            // 存储到 sessionStorage
            sessionStorage.setItem("shareResource", JSON.stringify(shareResource))

            // 跳转到分享页面
            router.push("/community/share")
        } catch (error) {
            console.error("准备分享数据失败:", error)
            toast({
                title: "分享失败",
                description: "请稍后重试"
            })
        }
    }

    return (
        <div className="min-h-screen bg-black text-white">
            {/* 视频播放区域 */}
            <div className="relative w-full bg-black">
                <div className="container mx-auto px-4 py-4">
                    <div className="relative aspect-video bg-black overflow-hidden rounded-lg">
                        <video
                            ref={videoRef}
                            src={mvDetail.url}
                            poster={mvDetail.cover}
                            className="w-full h-full object-contain"
                            onTimeUpdate={handleTimeUpdate}
                            onLoadedMetadata={handleLoadedMetadata}
                            onClick={togglePlay}
                        />

                        {/* 视频控制层 */}
                        <div className="absolute inset-0 flex flex-col justify-between p-4 bg-gradient-to-b from-black/50 via-transparent to-black/50 opacity-0 hover:opacity-100 transition-opacity">
                            {/* 顶部控制栏 */}
                            <div className="flex justify-between items-center">
                                <h1 className="text-xl font-bold truncate">{mvDetail.title}</h1>
                                <div className="flex items-center space-x-2">
                                    <Button variant="ghost" size="icon" className="text-white">
                                        <ListPlus className="h-5 w-5" />
                                    </Button>
                                    <Button variant="ghost" size="icon" className="text-white">
                                        <Download className="h-5 w-5" />
                                    </Button>
                                </div>
                            </div>

                            {/* 中间播放按钮 */}
                            <div className="absolute inset-0 flex items-center justify-center">
                                {!isPlaying && (
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-16 w-16 rounded-full bg-white/20 text-white hover:bg-white/30"
                                        onClick={togglePlay}
                                    >
                                        <Play className="h-8 w-8" />
                                    </Button>
                                )}
                            </div>

                            {/* 底部控制栏 */}
                            <div className="space-y-2">
                                {/* 进度条 */}
                                <div className="flex items-center space-x-2">
                                    <span className="text-xs">{formatDuration(currentTime * 1000)}</span>
                                    <input
                                        type="range"
                                        min="0"
                                        max={duration || 100}
                                        value={currentTime}
                                        onChange={handleSeek}
                                        className="flex-1 h-1 bg-white/30 rounded-full appearance-none [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white"
                                    />
                                    <span className="text-xs">{formatDuration(duration * 1000)}</span>
                                </div>

                                {/* 控制按钮 */}
                                <div className="flex justify-between items-center">
                                    <div className="flex items-center space-x-4">
                                        <Button variant="ghost" size="icon" className="text-white">
                                            <SkipBack className="h-5 w-5" />
                                        </Button>
                                        <Button variant="ghost" size="icon" className="text-white" onClick={togglePlay}>
                                            {isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
                                        </Button>
                                        <Button variant="ghost" size="icon" className="text-white">
                                            <SkipForward className="h-5 w-5" />
                                        </Button>
                                    </div>

                                    <div className="flex items-center space-x-4">
                                        <Button variant="ghost" size="icon" className="text-white" onClick={toggleMute}>
                                            {isMuted ? <VolumeX className="h-5 w-5" /> : <Volume2 className="h-5 w-5" />}
                                        </Button>
                                        <Button variant="ghost" size="icon" className="text-white" onClick={handleFullscreen}>
                                            <Maximize2 className="h-5 w-5" />
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* 内容区域 */}
            <div className="bg-background text-foreground">
                <div className="container mx-auto px-4 py-6">
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                        {/* 左侧信息区域 */}
                        <div className="lg:col-span-2 space-y-6">
                            {/* MV信息 */}
                            <div>
                                <h1 className="text-2xl font-bold mb-2">{mvDetail.title}</h1>
                                <div className="flex items-center space-x-4 mb-4">
                                    <Link href={`/artist/${mvDetail.artistId}`} className="flex items-center space-x-2">
                                        <Avatar className="h-8 w-8">
                                            <AvatarImage src="/placeholder.svg" alt={mvDetail.artists} />
                                            <AvatarFallback>{mvDetail.artists[0]}</AvatarFallback>
                                        </Avatar>
                                        <span className="font-medium">{mvDetail.artists}</span>
                                    </Link>
                                    <span className="text-sm text-muted-foreground">发布于 {mvDetail.releaseDate}</span>
                                </div>
                                <div className="flex flex-wrap gap-4 mb-4">
                                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                                        <Play className="h-4 w-4" />
                                        <span>{formatNumber(mvDetail.playCount)}</span>
                                    </div>
                                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                                        <Heart className="h-4 w-4" />
                                        <span>{formatNumber(mvDetail.likes)}</span>
                                    </div>
                                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                                        <MessageSquare className="h-4 w-4" />
                                        <span>{formatNumber(mvDetail.comments)}</span>
                                    </div>
                                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                                        <Share2 className="h-4 w-4" />
                                        <span>{formatNumber(mvDetail.shares)}</span>
                                    </div>
                                </div>
                                <div className="flex space-x-2">
                                    <Button
                                        variant={isLiked ? "default" : "outline"}
                                        className={isLiked ? "bg-red-500 hover:bg-red-600" : ""}
                                        onClick={toggleLike}
                                    >
                                        <Heart className={`h-4 w-4 mr-2 ${isLiked ? "fill-current" : ""}`} />
                                        {isLiked ? "已喜欢" : "喜欢"}
                                    </Button>
                                    <Button variant="outline">
                                        <MessageSquare className="h-4 w-4 mr-2" />
                                        评论
                                    </Button>
                                    <Button variant="outline" onClick={handleShare}>
                                        <Share2 className="h-4 w-4 mr-2" />
                                        分享
                                    </Button>
                                    <Button variant="outline">
                                        <Download className="h-4 w-4 mr-2" />
                                        下载
                                    </Button>
                                </div>
                            </div>

                            <Separator />

                            {/* 标签 */}
                            <div>
                                <h3 className="text-sm font-medium text-muted-foreground mb-2">标签</h3>
                                <div className="flex flex-wrap gap-2">
                                    {mvDetail.tags.map((tag, index) => (
                                        <span key={index} className="px-3 py-1 bg-secondary text-secondary-foreground rounded-full text-xs">
                      {tag}
                    </span>
                                    ))}
                                </div>
                            </div>

                            <Separator />

                            {/* 简介和歌词 */}
                            <Tabs defaultValue="description" className="w-full">
                                <TabsList className="mb-4">
                                    <TabsTrigger value="description">简介</TabsTrigger>
                                    <TabsTrigger value="lyrics">歌词</TabsTrigger>
                                </TabsList>
                                <TabsContent value="description" className="text-sm leading-relaxed">
                                    {mvDetail.description}
                                </TabsContent>
                                <TabsContent value="lyrics" className="text-sm leading-relaxed">
                                    <div className="space-y-2">
                                        {mvDetail.lyrics.map((line, index) => (
                                            <p key={index} className="py-1">
                                                {line.text}
                                            </p>
                                        ))}
                                    </div>
                                </TabsContent>
                            </Tabs>

                            <Separator />

                            {/* 评论区 - 使用共用组件 */}
                            <CommentSection contentId={id as string} contentType="mv" />
                        </div>

                        {/* 右侧相关推荐 */}
                        <div className="space-y-6">
                            <div>
                                <h2 className="text-xl font-bold mb-4">相关推荐</h2>
                                <div className="space-y-4">
                                    {relatedMVs.map((mv) => (
                                        <Link href={`/mv/${mv.id}`} key={mv.id} className="flex space-x-3 group">
                                            <div className="relative w-32 h-20 overflow-hidden rounded">
                                                <Image
                                                    src={mv.cover || "/placeholder.svg"}
                                                    alt={mv.title}
                                                    fill
                                                    className="object-cover group-hover:scale-105 transition-transform"
                                                />
                                                <div className="absolute bottom-1 right-1 bg-black/70 text-white text-xs px-1 rounded">
                                                    {formatDuration(mv.duration * 1000)}
                                                </div>
                                            </div>
                                            <div className="flex-1">
                                                <h3 className="font-medium line-clamp-2 group-hover:text-primary transition-colors">
                                                    {mv.title}
                                                </h3>
                                                <p className="text-sm text-muted-foreground mt-1">{mv.artists}</p>
                                                <p className="text-xs text-muted-foreground mt-1">{formatNumber(mv.playCount)} 次播放</p>
                                            </div>
                                        </Link>
                                    ))}
                                </div>
                            </div>

                            <Separator />

                            {/* 艺人其他MV */}
                            <div>
                                <h2 className="text-xl font-bold mb-4">艺人其他MV</h2>
                                <div className="space-y-4">
                                    {relatedMVs.map((mv) => (
                                        <Link href={`/mv/${mv.id}`} key={mv.id} className="flex space-x-3 group">
                                            <div className="relative w-32 h-20 overflow-hidden rounded">
                                                <Image
                                                    src={mv.cover || "/placeholder.svg"}
                                                    alt={mv.title}
                                                    fill
                                                    className="object-cover group-hover:scale-105 transition-transform"
                                                />
                                                <div className="absolute bottom-1 right-1 bg-black/70 text-white text-xs px-1 rounded">
                                                    {formatDuration(mv.duration * 1000)}
                                                </div>
                                            </div>
                                            <div className="flex-1">
                                                <h3 className="font-medium line-clamp-2 group-hover:text-primary transition-colors">
                                                    {mv.title}
                                                </h3>
                                                <p className="text-xs text-muted-foreground mt-1">{formatNumber(mv.playCount)} 次播放</p>
                                            </div>
                                        </Link>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

